using admin.application.Services;
using admin.application.Common;
using admin.core.Entities.App;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using Serilog;

namespace admin.api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize] // 所有图片接口都需要token验证
    public class ImageController : ControllerBase
    {
        private readonly IAppImageService _appImageService;
        private readonly AppAuthService _authService;
        private readonly IWebHostEnvironment _env;

        public ImageController(IAppImageService appImageService, AppAuthService authService, IWebHostEnvironment env)
        {
            _appImageService = appImageService;
            _authService = authService;
            _env = env;
        }

        [HttpPost("create-test-user")]
        public async Task<IActionResult> CreateTestUser()
        {
            try
            {
                // 调用认证服务创建测试用户
                await _authService.RegisterAsync("testuser", "123456");
                
                // 查找刚创建的用户
                var user = await _authService.LoginAsync("testuser", "123456");
                if (user != null)
                {
                    var result = new
                    {
                        userId = user.Id,
                        username = user.UserName,
                        note = "现在可以使用这个用户ID进行图片上传测试"
                    };
                    
                    return Ok(ResponseResult<object>.Ok(result, "测试用户创建成功"));
                }
                else
                {
                    return BadRequest(ResponseResult<object>.Fail("用户创建失败", 400));
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ResponseResult<object>.Fail($"创建测试用户失败: {ex.Message}", 500));
            }
        }

        [HttpPost("test-delete-avatar/{userId}")]
        public async Task<IActionResult> TestDeleteAvatar(string userId)
        {
            try
            {
                if (!Guid.TryParse(userId, out var parsedUserId))
                {
                    return BadRequest(ResponseResult<object>.Fail("用户ID格式无效", 400));
                }

                Log.Information("[测试删除头像] 开始测试删除用户 {UserId} 的头像", parsedUserId);
                
                // 调用删除头像方法
                await DeleteUserExistingAvatar(parsedUserId);
                
                var result = new
                {
                    userId = parsedUserId,
                    message = "头像删除测试完成，请查看控制台日志"
                };
                
                return Ok(ResponseResult<object>.Ok(result, "头像删除测试完成"));
            }
            catch (Exception ex)
            {
                return BadRequest(ResponseResult<object>.Fail($"头像删除测试失败: {ex.Message}", 500));
            }
        }

        [HttpGet("debug-user-images/{userId}")]
        public async Task<IActionResult> DebugUserImages(string userId, [FromQuery] bool includeDeleted = false)
        {
            try
            {
                if (!Guid.TryParse(userId, out var parsedUserId))
                {
                    return BadRequest(ResponseResult<object>.Fail("用户ID格式无效", 400));
                }

                Log.Information("[调试] 查询用户 {UserId} 的图片信息，包含已删除: {IncludeDeleted}", parsedUserId, includeDeleted);
                
                // 获取用户的所有图片（默认只查未删除的）
                var images = await _appImageService.GetImagesByUserIdAsync(parsedUserId);
                if (!includeDeleted)
                {
                    images = images.Where(img => !img.IsDeleted);
                }
                
                var imageList = new List<object>();
                foreach (var image in images)
                {
                    var filePath = Path.Combine(_env.WebRootPath, "images", image.FileName);
                    var fileExists = System.IO.File.Exists(filePath);
                    
                    imageList.Add(new
                    {
                        id = image.Id,
                        fileName = image.FileName,
                        originalFileName = image.OriginalFileName,
                        filePath = image.FilePath,
                        url = image.Url,
                        tags = image.Tags,
                        description = image.Description,
                        fileSize = image.FileSize,
                        contentType = image.ContentType,
                        isActived = image.IsActived,
                        isDeleted = image.IsDeleted,
                        createdAt = image.CreatedAt,
                        updatedAt = image.UpdatedAt,
                        physicalFileExists = fileExists,
                        physicalFilePath = filePath
                    });
                }
                
                var result = new
                {
                    userId = parsedUserId,
                    totalImages = imageList.Count,
                    includeDeleted = includeDeleted,
                    note = includeDeleted ? "包含已删除的记录" : "仅显示未删除的记录",
                    images = imageList
                };
                
                return Ok(ResponseResult<object>.Ok(result, "用户图片调试信息"));
            }
            catch (Exception ex)
            {
                return BadRequest(ResponseResult<object>.Fail($"获取用户图片调试信息失败: {ex.Message}", 500));
            }
        }

        [HttpPost("upload")]
        public async Task<IActionResult> Upload([FromForm] IFormFile file, [FromForm] string userId, [FromForm] string? description = null, [FromForm] string? tags = null)
        {
            // 验证文件
            if (file == null || file.Length == 0)
                return BadRequest(ResponseResult<object>.Fail("请选择要上传的图片文件", 400));

            // 验证用户ID格式
            if (string.IsNullOrEmpty(userId) || !Guid.TryParse(userId, out var parsedUserId))
            {
                return BadRequest(ResponseResult<object>.Fail("用户ID格式无效，请提供有效的GUID格式", 400));
            }

            // 先验证用户ID是否可以查到用户
            var user = await _authService.GetUserByIdAsync(parsedUserId);
            if (user == null)
            {
                return BadRequest(ResponseResult<object>.Fail($"用户不存在，用户ID: {parsedUserId}", 400));
            }

            // 验证用户是否已激活且未删除
            if (!user.IsActived || user.IsDeleted)
            {
                return BadRequest(ResponseResult<object>.Fail($"用户状态异常，无法上传图片。用户ID: {parsedUserId}, 是否激活: {user.IsActived}, 是否删除: {user.IsDeleted}", 400));
            }

            try
            {
                // 检查是否是头像上传（tags包含"avatar"）
                bool isAvatarUpload = !string.IsNullOrEmpty(tags) && tags.ToLower().Contains("avatar");
                
                // 如果是头像上传，先删除用户之前的头像（物理删除+伪删除）
                if (isAvatarUpload)
                {
                    await DeleteUserExistingAvatar(parsedUserId);
                }

                var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
                // 使用 WebRootPath 确保保存到正确的 wwwroot 目录
                var uploads = Path.Combine(_env.WebRootPath, "images");
                if (!Directory.Exists(uploads))
                    Directory.CreateDirectory(uploads);
                var filePath = Path.Combine(uploads, fileName);

                // 日志：输出图片保存路径
                Log.Information("[图片上传] WebRootPath: {Path}", _env.WebRootPath);
                Log.Information("[图片上传] 当前目录: {Path}", Directory.GetCurrentDirectory());
                Log.Information("[图片上传] 图片保存路径: {Path}", filePath);

                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                var url = $"/api/Image/file/{fileName}";
                var uploadTime = DateTime.UtcNow;

                // 创建AppImage对象，确保所有字段都有值
                var image = new AppImage
                {
                    Id = Guid.NewGuid(),
                    FileName = fileName,
                    OriginalFileName = file.FileName,
                    FilePath = filePath,
                    FileExtension = Path.GetExtension(file.FileName),
                    FileSize = file.Length,
                    ContentType = file.ContentType,
                    Url = url,
                    UploadTime = uploadTime,
                    Tags = tags,
                    Description = description,
                    UserId = user.Id, // 使用验证过的真实用户ID
                    IsActived = true,
                    IsDeleted = false,
                    CreatedAt = DateTime.UtcNow,
                    UpdatedAt = DateTime.UtcNow,
                    CreatedBy = user.Id, // 使用验证过的真实用户ID
                    UpdatedBy = user.Id, // 使用验证过的真实用户ID
                    Remarks = null
                };

                // 保存图片信息到数据库
                await _appImageService.SaveImageInfoAsync(image);

                var result = new
                {
                    fileName,
                    url,
                    userId = user.Id,
                    username = user.UserName,
                    isAvatar = isAvatarUpload
                };

                return Ok(ResponseResult<object>.Ok(result, "图片上传成功"));
            }
            catch (Exception ex)
            {
                return BadRequest(ResponseResult<object>.Fail($"图片上传失败: {ex.Message}", 500));
            }
        }

        // 获取图片文件
         [AllowAnonymous]
        [HttpGet("file/{fileName}")]    
        public IActionResult GetImageFile(string fileName)
        {
            var imagePath = Path.Combine(_env.WebRootPath, "images", fileName);
            if (!System.IO.File.Exists(imagePath))
                return NotFound();
            try
            {
                var filePath = Path.Combine(_env.WebRootPath, "images", fileName);
                if (!System.IO.File.Exists(filePath))
                {
                    return NotFound(ResponseResult<object>.Fail("图片文件不存在", 404));
                }
                var contentType = GetContentType(fileName);
                return PhysicalFile(filePath, contentType);
            }
            catch (Exception ex)
            {
                return BadRequest(ResponseResult<object>.Fail($"获取图片失败: {ex.Message}", 500));
            }
        }

        // 获取图片信息
        [HttpGet("info/{fileName}")]
        public async Task<IActionResult> GetImageInfo(string fileName)
        {
            try
            {
                var image = await _appImageService.GetImageByFileNameAsync(fileName);
                if (image == null)
                {
                    return NotFound(ResponseResult<object>.Fail("图片信息不存在", 404));
                }

                return Ok(ResponseResult<object>.Ok(image, "获取图片信息成功"));
            }
            catch (Exception ex)
            {
                return BadRequest(ResponseResult<object>.Fail($"获取图片信息失败: {ex.Message}", 500));
            }
        }

        // 获取用户的图片列表
        [HttpGet("user/{userId}")]
        public async Task<IActionResult> GetUserImages(string userId)
        {
            try
            {
                if (!Guid.TryParse(userId, out var parsedUserId))
                {
                    return BadRequest(ResponseResult<object>.Fail("用户ID格式无效", 400));
                }

                var images = await _appImageService.GetImagesByUserIdAsync(parsedUserId);
                return Ok(ResponseResult<object>.Ok(images, "获取用户图片列表成功"));
            }
            catch (Exception ex)
            {
                return BadRequest(ResponseResult<object>.Fail($"获取用户图片列表失败: {ex.Message}", 500));
            }
        }

        // 获取用户头像
        [HttpGet("avatar/{userId}")]
        public async Task<IActionResult> GetUserAvatar(string userId)
        {
            try
            {
                if (!Guid.TryParse(userId, out var parsedUserId))
                {
                    return BadRequest(ResponseResult<object>.Fail("用户ID格式无效", 400));
                }

                // 获取用户的所有图片
                var images = await _appImageService.GetImagesByUserIdAsync(parsedUserId);
                
                // 查找标记为头像的图片（tags包含"avatar"）
                var avatarImage = images.FirstOrDefault(img => 
                    !string.IsNullOrEmpty(img.Tags) && 
                    img.Tags.ToLower().Contains("avatar"));

                if (avatarImage != null)
                {
                    var result = new
                    {
                        fileName = avatarImage.FileName,
                        url = $"/api/Image/file/{avatarImage.FileName}",
                        hasAvatar = true
                    };
                    return Ok(ResponseResult<object>.Ok(result, "获取用户头像成功"));
                }
                else
                {
                    var result = new
                    {
                        fileName = (string?)null,
                        url = (string?)null,
                        hasAvatar = false
                    };
                    return Ok(ResponseResult<object>.Ok(result, "用户没有头像"));
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ResponseResult<object>.Fail($"获取用户头像失败: {ex.Message}", 500));
            }
        }

        // 删除图片
        [HttpDelete("{fileName}")]
        public async Task<IActionResult> DeleteImage(string fileName)
        {
            try
            {
                var image = await _appImageService.GetImageByFileNameAsync(fileName);
                if (image == null)
                {
                    return NotFound(ResponseResult<object>.Fail("图片不存在", 404));
                }

                // 先删除物理文件
                var filePath = Path.Combine(_env.WebRootPath, "images", fileName);
                if (System.IO.File.Exists(filePath))
                {
                    try
                    {
                        System.IO.File.Delete(filePath);
                        Log.Information("成功删除物理文件: {FilePath}", filePath);
                    }
                    catch (Exception fileEx)
                    {
                        Log.Error(fileEx, "删除物理文件失败");
                        // 继续执行，不因为文件删除失败而中断整个删除流程
                    }
                }
                else
                {
                    Log.Information("物理文件不存在，跳过删除: {FilePath}", filePath);
                }

                // 再删除数据库记录
                var deleteResult = await _appImageService.DeleteImageAsync(image.Id);
                if (deleteResult)
                {
                    Log.Information("成功删除数据库记录: {ImageId}", image.Id);
                    return Ok(ResponseResult<object>.Ok(null, "图片删除成功"));
                }
                else
                {
                    Log.Information("删除数据库记录失败: {ImageId}", image.Id);
                    return BadRequest(ResponseResult<object>.Fail("删除数据库记录失败", 500));
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ResponseResult<object>.Fail($"删除图片失败: {ex.Message}", 500));
            }
        }

        // 批量获取用户头像
        [HttpPost("avatars-by-userids")]
        public async Task<IActionResult> GetAvatarsByUserIds([FromBody] List<Guid> userIds)
        {
            if (userIds == null || userIds.Count == 0)
                return BadRequest(ResponseResult<object>.Fail("用户ID数组不能为空", 400));

            // 调用Service层批量查询
            var avatarDict = await _appImageService.GetAvatarsByUserIdsAsync(userIds);

            // 组装响应
            var result = userIds.Select(uid => new {
                userId = uid,
                avatar = avatarDict.TryGetValue(uid, out var avatar) && avatar != null ? new {
                    fileName = avatar.FileName,
                    url = $"/api/Image/file/{avatar.FileName}",
                    hasAvatar = true
                } : new {
                    fileName = (string?)null,
                    url = (string?)null,
                    hasAvatar = false
                }
            });
            return Ok(ResponseResult<object>.Ok(result, "批量获取用户头像成功"));
        }

        private string GetContentType(string fileName)
        {
            var extension = Path.GetExtension(fileName).ToLowerInvariant();
            return extension switch
            {
                ".jpg" or ".jpeg" => "image/jpeg",
                ".png" => "image/png",
                ".gif" => "image/gif",
                ".bmp" => "image/bmp",
                ".webp" => "image/webp",
                _ => "application/octet-stream"
            };
        }

        /// <summary>
        /// 删除用户现有的头像
        /// </summary>
        /// <param name="userId">用户ID</param>
        private async Task DeleteUserExistingAvatar(Guid userId)
        {
            try
            {
                Log.Information("[删除头像] _env.WebRootPath: {WebRootPath}", _env.WebRootPath);
                var imagesDir = Path.Combine(_env.WebRootPath, "images");
                Log.Information("[删除头像] images目录存在: {Exists}", Directory.Exists(imagesDir));
                Log.Information("[删除头像] 开始删除用户 {UserId} 的现有头像", userId);
                // 先查询数据库中用户的所有图片
                var images = await _appImageService.GetImagesByUserIdAsync(userId);
                Log.Information("[删除头像] 用户 {UserId} 共有 {TotalImages} 张图片", userId, images.Count());
                // 查找所有头像（不管 IsDeleted）
                var avatars = images.Where(img =>
                    !string.IsNullOrEmpty(img.Tags) &&
                    img.Tags.ToLower().Contains("avatar")).ToList();
                if (avatars.Count == 0)
                {
                    Log.Information("[删除头像] 用户 {UserId} 没有找到任何头像记录", userId);
                    return;
                }
                foreach (var avatar in avatars)
                {
                    Log.Information("[调试] _env.WebRootPath: {Path}", _env.WebRootPath);
                    Log.Information("[调试] avatar.FileName: {FileName}", avatar.FileName);
                    var filePath = Path.Combine(_env.WebRootPath, "images", avatar.FileName);
                    Log.Information("[调试] 拼接的完整路径: {FilePath}", filePath);
                    Log.Information("[删除头像] 物理文件路径: {FilePath}, Exists: {Exists}", filePath, System.IO.File.Exists(filePath));
                    try
                    {
                        if (System.IO.File.Exists(filePath))
                        {
                            System.IO.File.Delete(filePath);
                            Log.Information("[删除头像] 成功删除物理文件: {FilePath}", filePath);
                        }
                        else
                        {
                            Log.Information("[删除头像] 物理文件不存在，跳过删除: {FilePath}", filePath);
                        }
                    }
                    catch (Exception fileEx)
                    {
                        Log.Error(fileEx, "[删除头像] 删除物理文件异常");
                    }
                    // 只删除未被逻辑删除的数据库记录
                    if (!avatar.IsDeleted)
                    {
                        try
                        {
                            Log.Information("[删除头像] 开始删除数据库记录: {AvatarId}", avatar.Id);
                            var deleteResult = await _appImageService.DeleteImageAsync(avatar.Id);
                            if (deleteResult)
                            {
                                Log.Information("[删除头像] 成功删除数据库记录: {AvatarId}", avatar.Id);
                            }
                            else
                            {
                                Log.Information("[删除头像] 删除数据库记录失败: {AvatarId}", avatar.Id);
                            }
                        }
                        catch (Exception dbEx)
                        {
                            Log.Error(dbEx, "[删除头像] 删除数据库记录异常");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // 记录错误但不抛出异常，避免影响新头像的上传
                Log.Error(ex, "[删除头像] 删除用户现有头像时出错");
            }
        }
    }
} 